package com.example.servlet.student;

import com.example.bean.Student2;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-02 14:57
 **/
@WebServlet("/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student2 student = new Student2();
        ServletContext context = getServletContext();
        String dir = context.getRealPath("/student");
        File file = new File(dir);
        file.mkdirs();
        try (BufferedWriter bis = new BufferedWriter(
                new FileWriter(new File(file, "student.txt"), true));) {
            BeanUtils.populate(student, req.getParameterMap());
            String username = student.getUsername();
            int age = student.getAge();
            int score = student.getScore();
            System.out.println(student);

            bis.write(username + "," + age + "," + score);
            bis.newLine();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
